package com.test.mchelepesa.util_rice.analytics_rice.util_rice

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import androidx.core.content.edit
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseApplication_rice
import com.test.mchelepesa.constant_rice.Constant_rice
import com.test.mchelepesa.util_rice.StringUtil_rice
import java.sql.DriverManager.println
import java.util.UUID

object AdvertIdUtil_rice {

    /** sp key gaid */
    const val SP_KEY_GAID = "GAID"

    /** sp key gaid enable */
    const val SP_KEY_AD_ENABLE = "ENABLE"

    /** 初始化sp */
    private lateinit var mSp: SharedPreferences

    /** 是否允许广告跟踪 */
    private var mAdEnabled: Int = 0

    /** 广告id, 每个接口中的advertId字段 */
    private var mAdId: String = ""

    /**
     * 初始化
     *
     * @param context Application
     */
    fun init(context: Application, success: (String, Int) -> Unit) {
        try {
            mSp = context.getSharedPreferences(
                Constant_rice.PRODUCT,
                Context.MODE_PRIVATE
            )

            mAdId = mSp.getString(SP_KEY_GAID, "") ?: ""
            mAdEnabled = mSp.getInt(SP_KEY_AD_ENABLE, 0)

            if (mAdId.isBlank()) {
                Thread {
                    try {
                        if (Looper.getMainLooper() != Looper.myLooper()) {
                            val advertisingIdClient =
                                AdvertisingIdClient.getAdvertisingIdInfo(context)
                            val enable = if (advertisingIdClient.isLimitAdTrackingEnabled) 1 else 0
                            mAdId = advertisingIdClient.id ?: ""
                            mAdEnabled = enable

                            mSp.edit {
                                putInt(SP_KEY_AD_ENABLE, mAdEnabled)
                                putString(SP_KEY_GAID, mAdId)
                                commit()
                            }
                            println("mAdId=$mAdId mIsLimitAdTrackingEnabled=$mAdEnabled")

                            if (mAdId.isNotBlank()) {
                                Handler(Looper.getMainLooper()).post {
                                    //回调通知
                                    success.invoke(mAdId, mAdEnabled)
                                }
                            }
                        } else {
                            println("init GAID ERROR!!! Cannot call in the main thread, You must call in the other thread")
                        }
                    } catch (e: Exception) {
                        StringUtil_rice.printException(e)
                    }
                }.start()
            }

        } catch (e: Exception) {
            //
        }
    }

    /**
     * 获取广告id
     *
     * @return 广告id
     */
    fun getAdId(): String {
        return mAdId
    }

    /**
     * 获取是否限制广告跟踪
     *
     * @return 限制状态
     */
    fun getAdEnabled(): Int {
        return mAdEnabled
    }

    /**
     * 获取安卓id
     *
     * @return 安卓id
     */
    fun getAndroidId(): String {
        return try {
            val androidId = Settings.System.getString(
                BaseApplication_rice.gApplication_rice().contentResolver,
                Settings.Secure.ANDROID_ID
            )

            if (androidId.isBlank() || androidId.contains("00000000")) {
                generateFallbackId()
            } else {
                androidId
            }
        } catch (e: Exception) {
            //
            generateFallbackId()
        }
    }

    private fun generateFallbackId(): String {
        return UUID.randomUUID().toString()
    }
}